/**
 * 支付管理-发票管理
 */
var queryInvoicesSearch = function() {
	var queryInvoicesFieldSet = new Ext.form.FieldSet({
				id : 'queryInvoicesFieldSet',
				title : '查询条件',
				collapsible : true,// 可折叠
				buttonAlign : 'center',
				keys : [{
							key : 13, // 13代表回车
							fn : queryInvoices,
							scope : this
						}],
				items : [{
					layout : 'column',
					border : false,
					items : [{
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '订单编号',
											name : "id"
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '订单编码',
											name : "orderCode"
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
									xtype : 'localcommonbox',
									anchor : '100%',
									fieldLabel : '是否已开发票',
									hiddenName : 'isReferenceInvoice',
									loaclarr : [['0', '否'], ['1', '是'],
											['', '全部']],
									value : 0
								}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
									layout : 'column',
									border : false,
									items : [{
												text : '查询',
												xtype : 'button',
												width : 80,
												handler : function() {
													queryInvoices();
												},
												style : {
													marginLeft : "100px",
													marginRight : "10px"
												}
											}, {
												text : '重置',
												xtype : 'button',
												width : 80,
												handler : function() {
													Ext
															.getCmp('queryInvoicesForm')
															.getForm().reset();
												}
											}]
								}]
							}]
				}]
			});
	fieldSetListeners(['queryInvoicesFieldSet', 'queryInvoicesForm',
					'invoiceManagerGrid'], [0.12, 0.88]);

	var queryInvoicesForm = new Ext.form.FormPanel({
				id : 'queryInvoicesForm',
				anchor : '100% 12%',
				frame : true,
				labelAlign : 'right',
				bodyBorder : false,
				items : [queryInvoicesFieldSet]
			});
	return queryInvoicesForm;
};

/**
 * grids
 */
var invoiceManagerGrid = function() {
	var invoiceManagerSm = new Ext.grid.CheckboxSelectionModel({
				checkOnly : true,
				renderer : function(v, p, record) {
					var isReferenceInvoice = record.get('isReferenceInvoice');
					if (isReferenceInvoice != 1) {
						return '<div class="x-grid3-row-checker">&#160;</div>';
					} else {
						return '';
					}
				},
				listeners : {
					beforerowselect : function(SelectionModel, rowIndex,
							keepExisting, record) {
						var isReferenceInvoice = record
								.get('isReferenceInvoice');
						if (isReferenceInvoice != 1) {
							return true;
						} else {
							return false;
						}
					}
				}

			});// 创建选择模式对象
	// 定义表的每列（对应表头信息）
	var invoiceManagerCm = new Ext.grid.ColumnModel([invoiceManagerSm,
			new Ext.grid.RowNumberer(), {
				dataIndex : "id",
				header : "订单编号",
				sortable : true,
				width : 70
			}, {
				dataIndex : "orderCode",
				header : "订单编码",
				sortable : true,
				width : 160,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="订单编码:" ext:qtip="' + value
								+ '"';
						return value;
					}
				}
			}, {
				dataIndex : "isNeedInvoice",
				header : "是否需要发票",
				sortable : true,
				width : 100,
				renderer : function(value) {
					return PmsUtil.isNeedInvoice(value);
				}
			}, {
				dataIndex : "invoiceTitle",
				header : "发票抬头",
				sortable : true,
				width : 120,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="发票抬头:" ext:qtip="' + value
								+ '"';
						return value;
					}
				}
			}, {
				dataIndex : "invoiceContent",
				header : "发票内容",
				sortable : true,
				width : 80,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="发票内容:" ext:qtip="' + value
								+ '"';
						return value;
					}
				}
			}, {
				dataIndex : "isReferenceInvoice",
				header : "是否已开发票",
				sortable : true,
				width : 100,
				renderer : function(value) {
					return PmsUtil.IsDafault(value);
				}
			}, {
				dataIndex : "payAmount",
				header : "开票金额",
				sortable : true,
				width : 80,
				renderer : function(value) {
					return PmsUtil.Price(value);
				}
			}, {
				dataIndex : "consignee",
				header : "收货人",
				sortable : true,
				width : 70
			}, {
				dataIndex : "consignPhone",
				header : "收货电话",
				sortable : true,
				width : 100
			}, {
				dataIndex : "consignAddress",
				header : "收货人地址",
				sortable : true,
				width : 140,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="收货人地址:" ext:qtip="' + value
								+ '"';
						return value;
					}
				}
			}, {
				header : "管理",
				width : 100,
				dataIndex : "id",
				sortable : false,
				renderer : function(j, i, g, m, h) {
					var l = g.data.id;
					var isReferenceInvoice = g.data.isReferenceInvoice;
					k = "";
					if (isGranted("invoiceManager_开票")) {
						if (isReferenceInvoice == "0") {
							k += '&nbsp;&nbsp;<a href="#" onclick="updIsReferenceInvoiceOne('
									+ l
									+ ','
									+ "1"
									+ ','
									+ "'已开票'"
									+ ')\" >开票</a>';
						}
					}
					return k;
				}
			}]);

	// 定义分析器
	var invoiceManagerReader = new Ext.data.JsonReader({
				totalProperty : "totalCount",
				root : "list",
				fields : [{
							name : "id"
						}, {
							name : "orderCode"
						}, {
							name : "isNeedInvoice"
						}, {
							name : "invoiceTitle"
						}, {
							name : "invoiceContent"
						}, {
							name : "payAmount"
						}, {
							name : "orderStatus"
						}, {
							name : "limitPayDate"
						}, {
							name : "payAmount"
						}, {
							name : "consignee"
						}, {
							name : "consignPhone"
						}, {
							name : "consignAddress"
						}, {
							name : 'isReferenceInvoice'
						}]

			});

	// 取数据store
	var invoiceViewStore = new Ext.data.Store({
				autoLoad : true,// 要加载数据必须设置为true
				proxy : new Ext.data.HttpProxy({
							url : __ctxPath + "/paymentManager/selectInvoices"
						}),
				remoteSort : false,
				baseParams : {
					start : 0,
					limit : 25,
					isNeedInvoice : 1
				},
				listeners : {
					beforeload : {
						fn : function(thiz, options) {
							Ext.apply(thiz.baseParams, Ext
											.getCmp('queryInvoicesForm')
											.getForm().getValues());
						}
					}
				},
				reader : invoiceManagerReader
			});

	// 定义grid的toolbar
	var invoiceTb = new Ext.Toolbar({
				id : "invoiceTb",
				height : 25,
				items : []
			});

	invoiceTb.add(new Ext.scm.Button({
				text : "刷 新",
				iconCls : "btn-refresh",
				width : 80,
				hsValue : "invoiceManager_刷新",
				pressed : true,
				handler : function() {
					queryInvoices();
				}
			}));
	invoiceTb.add(new Ext.Toolbar.Spacer());
	invoiceTb.add(new Ext.scm.Button({
				text : "已开票",
				iconCls : "btn-edit",
				width : 80,
				pressed : true,
				hsValue : "invoiceManager_批量已开票",
				listeners : {
					"click" : function() {
						updInvoiceReference();
					}
				}
			}));
	invoiceTb.add(new Ext.Toolbar.Spacer());
	invoiceTb.add(new Ext.scm.Button({
				text : "导出excel",
				iconCls : "btn-excel",
				width : 80,
				pressed : true,
				hsValue : "invoiceManager_批量导出",
				listeners : {
					"click" : function() {
						exportInvoicesToExcel();
					}
				}
			}));

	var invoiceManagerGrid = new Ext.grid.GridPanel({
				id : 'invoiceManagerGrid',
				store : invoiceViewStore,
				cm : invoiceManagerCm,
				sm : invoiceManagerSm,
				autoScroll : true,
				loadMask : true,
				stripeRows : true,
				columnLines : true,
				loadMask : {
					msg : "正在加载数据，请稍侯……"
				},
				viewConfig : {
					emptyText : '没有您想要的数据!'
				},
				anchor : '100% 88%',
				frame : true,
				tbar : invoiceTb,
				bbar : new PG.PagingBar({
							store : invoiceViewStore
						})
			});
	return invoiceManagerGrid;
};

// 查询
function queryInvoices() {
	var grid = Ext.getCmp("invoiceManagerGrid");
	var form = Ext.getCmp("queryInvoicesForm");
	if (form.getForm().isValid()) {
		grid.getStore().load();
	}
}

// 批量修改是否已开票
function updInvoiceReference() {
	var grid = Ext.getCmp("invoiceManagerGrid");
	var modiRecords = grid.getSelectionModel().getSelections();
	if (modiRecords.length == 0) {
		Ext.MessageBox.show({
					title : '提示',
					msg : '当前没有数据修改',
					buttons : Ext.MessageBox.OK,
					icon : Ext.MessageBox.WARNING
				});
		return;
	};

	var invoiceArr = new Array();
	for (var i = 0; i < modiRecords.length; i++) {
		var temrecord = new Ext.data.Record();
		temrecord.set("id", modiRecords[i].data.id);
		temrecord.set("isReferenceInvoice", 1);
		invoiceArr.push(temrecord.data);
	}
	var jsonList = Ext.encode(invoiceArr);

	Ext.Msg.confirm("信息确认", "是否批量修改为已开票？", function(btn) {
				if (btn == 'yes') {
					var optionMask = new Ext.LoadMask(Ext.getBody(), {
								msg : "正在处理,请稍后..."
							});
					optionMask.show();
					Ext.Ajax.request({
								url : __ctxPath
										+ "/paymentManager/updIsReferenceInvoice",
								params : {
									jsonList : Ext.util.Format
											.htmlDecode(jsonList).trim()
								},
								method : "post",
								success : function(response) {
									optionMask.hide();
									var jsonData = Ext.util.JSON
											.decode(response.responseText);
									if (jsonData.success) {
										Ext.MessageBox.show({
													title : "信息提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.INFO
												});
										queryInvoices();
									} else {
										Ext.MessageBox.show({
													title : "错误提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.ERROR
												});
									}
								},
								failure : function(response) {
									optionMask.hide();
									Ext.MessageBox.show({
												title : "操作信息",
												msg : "服务器请求异常,请稍后再试!",
												buttons : Ext.MessageBox.OK,
												icon : Ext.MessageBox.ERROR
											});
								}
							});
				}
			});

}

// 单个修改为已开票
function updIsReferenceInvoiceOne(orderId, isReferenceInvoice, message) {
	var invoiceArr = new Array();
	var temrecord = new Ext.data.Record();
	temrecord.set("id", orderId);
	temrecord.set("isReferenceInvoice", isReferenceInvoice);
	invoiceArr.push(temrecord.data);
	var jsonList = Ext.encode(invoiceArr);

	Ext.Msg.confirm("信息确认", "是否更改发票信息为" + message + "?", function(btn) {
				if (btn == "yes") {
					var optionMask = new Ext.LoadMask(Ext.getBody(), {
								msg : "正在处理,请稍后..."
							});
					optionMask.show();
					Ext.Ajax.request({
								url : __ctxPath
										+ "/paymentManager/updIsReferenceInvoice",
								params : {
									jsonList : Ext.util.Format
											.htmlDecode(jsonList).trim()
								},
								method : "post",
								success : function(response) {
									optionMask.hide();
									var jsonData = Ext.util.JSON
											.decode(response.responseText);
									if (jsonData.success) {
										Ext.MessageBox.show({
													title : "信息提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.INFO
												});
										queryInvoices();
									} else {
										Ext.MessageBox.show({
													title : "错误提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.ERROR
												});
									}
								},
								failure : function(response) {
									optionMask.hide();
									Ext.MessageBox.show({
												title : "操作信息",
												msg : "服务器请求异常,请稍后再试!",
												buttons : Ext.MessageBox.OK,
												icon : Ext.MessageBox.ERROR
											});
								}
							});
				}
			});
}

// 批量导出excel
function exportInvoicesToExcel() {
	var grid = Ext.getCmp("invoiceManagerGrid");
	var modiRecords = grid.getSelectionModel().getSelections();
	if (modiRecords.length == 0) {
		Ext.MessageBox.show({
					title : '提示',
					msg : '至少勾选一条需要导出的数据',
					buttons : Ext.MessageBox.OK,
					icon : Ext.MessageBox.WARNING
				});
		return;
	};
	var orderIds = "";
	$.each(modiRecords, function(i, item) {
				orderIds += item.data.id + ",";
			});
	if (orderIds.length > 0) {
		orderIds = orderIds.substring(0, orderIds.length - 1);
	}
	Ext.Msg.confirm("信息确认", "是否批量导出发票数据？", function(btn) {
				if (btn == 'yes') {
					document.location.href = __ctxPath
							+ "/paymentManager/exportInvoicesToExcel?orderIds="
							+ orderIds;
				}

			});

}

Ext.getCmp("centerTabPanel").getActiveTab().add(queryInvoicesSearch(),
		invoiceManagerGrid());
Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
